package com.ghsc.ghxc.jsb.ui.message.activity

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.AcivityYxFriendsBinding
import com.ghsc.ghxc.jsb.ui.message.bean.ChatDataResultBean
import com.ghsc.ghxc.jsb.view.NotDataView
import com.netease.nimlib.sdk.msg.MessageBuilder
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.yunxin.kit.chatkit.model.IMMessageInfo
import com.netease.yunxin.kit.chatkit.repo.ChatRepo
import com.netease.yunxin.kit.chatkit.ui.common.MessageHelper
import com.netease.yunxin.kit.chatkit.ui.dialog.ChatMessageForwardConfirmDialog
import com.netease.yunxin.kit.corekit.im.provider.FetchCallbackImpl
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.activity
 * 类名：YXFriendsListActivity
 * 创建时间：2024/5/13 13:57
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class YXFriendsListActivity : BaseVMActivity<MessageViewModel, AcivityYxFriendsBinding>() {
    override fun attachLayoutRes(): Int {
        return R.layout.acivity_yx_friends
    }

    override fun attachVMClass(): Class<MessageViewModel>? {
        return MessageViewModel::class.java
    }

    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }


    //
    private val mAdapter: ForwardListAdapter by lazy { ForwardListAdapter() }
    var mList = arrayListOf<ChatDataResultBean>()
    private var notDataView: View? = null


    var isCheckAll = false//全选 反选

    var bundle: Bundle? = null
    var type: Int = 0

    var messageInfo: IMMessageInfo? = null


    override fun initView() {
        bundle = intent.extras
        type = bundle!!.getInt("type", 0)
        messageInfo = bundle!!.getSerializable("messageInfo") as IMMessageInfo?
        binding.run {
            bar.topLeftView.setOnClickListener {
                finish()
            }
            bar.topTitle.text = if (type == 1) "我的好友" else "我的社群"
        }

//
        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        notDataView =
            NotDataView.notDataView(this, binding.rvList, binding.refreshLayout, "暂无数据")
        mAdapter.setOnItemClickListener { adapter, view, position ->
            mAdapter.data[position].isCheck = !mAdapter.data[position].isCheck
            mAdapter.notifyItemChanged(position)
            initDataCount()
        }

        initCheckData()
        binding.tvCheck.text = "全选( 0 )"
        initRefreshLayout()
        pageNo = 1
        getListData()
    }

    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }

    override fun initClickListener() {
        super.initClickListener()
        binding.llBtnCheck.setSingleClickListener {
            if (isCheckAll) {
                for (i in mAdapter.data.indices)
                    mAdapter.data[i].isCheck = false
                mAdapter.notifyDataSetChanged()
                isCheckAll = false
                initDataCount()
            } else {
                for (i in mAdapter.data.indices)
                    mAdapter.data[i].isCheck = true
                mAdapter.notifyDataSetChanged()
                isCheckAll = true
                initDataCount()
            }
        }

        binding.tvBtnNext.setSingleClickListener {
            if (listIds.size > 0) {
                val confirmDialog = ChatMessageForwardConfirmDialog.createForwardConfirmDialog(
                    if (type == 1) SessionTypeEnum.P2P else SessionTypeEnum.Team,
                    listIds,
                    messageInfo
                )
                confirmDialog.setCallback {
                    for (accId in listIds) {
                        val forwardMessage =
                            MessageBuilder.createForwardMessage(
                                messageInfo!!.message,
                                accId,
                                if (type == 1) SessionTypeEnum.P2P else SessionTypeEnum.Team
                            )
                        MessageHelper.clearAitAndReplyInfo(forwardMessage)
                        ChatRepo.sendMessage(
                            forwardMessage,
                            false,
                            object : FetchCallbackImpl<Void>() {
                                override fun onSuccess(param: Void?) {
                                }

                                override fun onFailed(code: Int) {
                                    if (code == 7101) {
                                        MessageHelper.saveLocalBlackTipMessageAndNotify(
                                            forwardMessage
                                        )
                                    }
                                }
                            })
                    }
                    finish()
                }
                confirmDialog.show(supportFragmentManager, "YXFriendsListActivity")
            } else showToast("请选择")
        }
    }


    private fun initCheckData() {
        if (isCheckAll) {
            binding.imgCheck.setImageResource(R.drawable.check_true_red)
        } else {
            binding.imgCheck.setImageResource(R.drawable.check_false_red)
        }
    }

    var listIds = arrayListOf<String>()
    private fun initDataCount() {
        listIds.clear()
        for (i in mAdapter.data.indices)
            if (mAdapter.data[i].isCheck) {
                listIds.add(if (type == 1) mAdapter.data[i].uid else mAdapter.data[i].tid)
            }
        if (listIds.size > 0) {
            binding.imgCheck.setImageResource(R.drawable.check_true_red)
        } else {
            binding.imgCheck.setImageResource(R.drawable.check_false_red)
        }
        binding.tvCheck.text = "全选(${listIds.size})"
    }


    private fun getListData() {

        if (type == 1) {
            val map: HashMap<String, Any> = HashMap()
            map["pindex"] = pageNo
            map["psize"] = 999999
            map["keyword"] = ""
            GsonUtil.mapToJsonStrObjEncryption(map)
                ?.let { it1 -> mViewModel.onFriendListMethod(it1) }
        } else {
            val map: HashMap<String, Any> = HashMap()
            map["pindex"] = pageNo
            map["psize"] = 999999
            GsonUtil.mapToJsonStrObjEncryption(map)
                ?.let { it1 -> mViewModel.onMyGroupListMethod(it1) }
        }


    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@YXFriendsListActivity) {
                binding.refreshLayout.finishRefresh()
                showToast(it)
            }
            againLoginMsg.observe(this@YXFriendsListActivity) {
                binding.refreshLayout.finishRefresh()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onMyGroupListData.observe(this@YXFriendsListActivity) {
                //我的群聊 列表
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()) {
                        mAdapter.replaceData(it.data.list)
                        mAdapter.setEmptyView(notDataView!!)
                    } else {
                        mAdapter.replaceData(it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
            }
            onFriendListData.observe(this@YXFriendsListActivity) {
                //我的群聊 列表
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()) {
                        mAdapter.replaceData(it.data.list)
                        mAdapter.setEmptyView(notDataView!!)
                    } else {
                        val list = arrayListOf<ChatDataResultBean>()
                        for (i in it.data.list.indices)
                            if (it.data.list[i].status == 1)
                                list.add(it.data.list[i])
                        mAdapter.replaceData(list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty()) {
                        val list = arrayListOf<ChatDataResultBean>()
                        for (i in it.data.list.indices)
                            if (it.data.list[i].status == 1)
                                list.add(it.data.list[i])
                        mAdapter.addData(list)
                    }
                }
            }

        }
    }


    inner class ForwardListAdapter : BaseQuickAdapter<ChatDataResultBean, BaseViewHolder>(
        R.layout.forward_item
    ) {
        override fun convert(helper: BaseViewHolder, item: ChatDataResultBean) {
            GlideUtil.ImageHeadLoad(this.context, item.headimg, helper.getView(R.id.userImgUrl))
            helper.setText(R.id.tvName, if (type == 1) item.nickname else item.name)
            helper.setImageResource(
                R.id.imgCheck,
                if (item.isCheck) R.drawable.check_true_red else R.drawable.check_false_red
            )
//            if (type==1){
//                if (item.level==0)
//                    helper.setGone(R.id.levelBg,true)
//                else {
//                    helper.setImageResource(R.id.levelBg, CharRongYunUtils.setImageLevelId(item.level))
//                        .setGone(R.id.levelBg,false)
//                }
//            }

        }
    }
}
